package web

import (
	"context"
	"strconv"

	"portal/internal/errorx"
	"portal/internal/svc"
	"portal/internal/types"
	"portal/model"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type JobFilterLogic struct {
	logx.Logger
	ctx          context.Context
	svcCtx       *svc.ServiceContext
	jobCateModel model.AwJobCategoriesModel
	cityModel    model.AwCityInfosModel
}

func NewJobFilterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *JobFilterLogic {
	return &JobFilterLogic{
		Logger:       logx.WithContext(ctx),
		ctx:          ctx,
		svcCtx:       svcCtx,
		jobCateModel: model.NewAwJobCategoriesModel(svcCtx.Orm),
		cityModel:    model.NewAwCityInfosModel(svcCtx.Orm),
	}
}

func (l *JobFilterLogic) JobFilter() (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	cityDtos, err := l.cityModel.GetAll(l.ctx, nil)
	if err != nil && err != sqlx.ErrNotFound {
		return nil, errorx.NewBizError(500, err.Error())
	}
	jobCateDtos, err := l.jobCateModel.GetAll(l.ctx, nil)
	if err != nil {
		return nil, errorx.NewBizError(500, err.Error())
	}

	jobCateVos := make([]*types.JobCategory, 0)
	for _, val := range jobCateDtos {
		jobCateVos = append(jobCateVos, &types.JobCategory{
			Id:         val.Id,
			Name:       val.Name,
			Depth:      val.Depth,
			EnName:     val.EnName,
			Parent:     strconv.Itoa(int(val.ParentId)),
			Children:   make([]*types.JobCategory, 0),
			CreateTime: val.CreateTime,
			UpdateTime: val.UpdateTime,
		})
	}
	jobCateSortedVos := &types.JobCategory{
		Id:   0,
		Name: "冠宇纺织公司",
	}
	TreeSort(jobCateVos, jobCateSortedVos)
	cityVos := make([]*types.City, 0)
	for _, val := range cityDtos {
		cityVos = append(cityVos, &types.City{
			Id:         val.Id,
			Code:       val.Code,
			Name:       val.Name,
			EnName:     val.EnName,
			CreateTime: val.CreateTime,
			UpdateTime: val.UpdateTime,
		})
	}

	return &types.CommonResponse{
		Status: 200,
		Msg:    "查询成功",
		Data: &types.JobFilterResponse{
			Citys:        cityVos,
			JobCategorys: jobCateSortedVos.Children,
		},
	}, nil
}

func TreeSort(data []*types.JobCategory, parent *types.JobCategory) {
	jobLastCates := make([]*types.JobCategory, 0)
	jobKeepCates := make([]*types.JobCategory, 0)
	for _, val := range data {
		parentId,_ := strconv.Atoi(val.Parent)
		if parent.Id == int64(parentId) {
			jobKeepCates = append(jobKeepCates, val)
		} else {
			jobLastCates = append(jobLastCates, val)
		}
	}
	parent.Children = jobKeepCates
	for i := 0; i < len(jobKeepCates); i++ {
		TreeSort(jobLastCates, jobKeepCates[i])
	}
}
